//index.js
//获取应用实例
var App = getApp()
Page({
  data: {
    goods:{},
    types: [],
    typeId: '',
    activeIndex: 0,
    userId: ''
  },
  onLoad (option) {
    this.integralType();
    let userId = wx.getStorageSync("userId");
    this.setData({userId});
    this.userInfo();
    setTimeout(() => {
      this.onPullDownRefresh();
    },500);
  },
  initData () {
    const goods = {
      items: [],
      total: '',
      params: {
        page : 1,
        pageCount: 20
      }
    }
    this.setData({ goods })
  },
  getList (cb) { // 获取积分商品列表
    let { goods,typeId } = this.data;
    let { params } = goods;
    params.typeId = typeId;
    App.HttpService.intList(params).then(res => {
      cb && cb()
      let data = res.data.data
      goods.items = [...goods.items, ...data.list]
      if (data.list.length > 0) {
        params.page = params.page + 1
        goods.total = data.counts
      }            
      this.setData({ goods })
    }, e => {
      cb && cb()
    })
  },
  toDetail (e) {
    let { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/integral-mall/detail/index?id=${id}`
    })
  },
  toExchange (e) {
    let detail = e.currentTarget.dataset
    detail.num = 1
    wx.setStorageSync('integral', detail)
    wx.navigateTo({
      url: '/pages/integral-mall/confirm/index'
    })
  },
  onPullDownRefresh () {
    wx.showNavigationBarLoading()
    this.initData()
    this.getList(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })
  },
  onReachBottom () {
    let goods = this.data.goods
    if (goods.items.length === goods.total) {
      return
    }
    this.getList()
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  // 获取所有的积分商品类别
  integralType () {
    App.HttpService.integralType().then(res => {
      if (res.data.code == 200) {
        let data = res.data.data;
        this.setData({types: data, typeId:data[0].id});
      }
    });
  },
  // 跳转到积分订单
  toIntegralOrder () {
    wx.navigateTo({
      url: '/pages/integral/list/index',
    })
  },
  // 选择类别
  chooseType (e) {
    let typeId = e.currentTarget.dataset.id;
    let rank = e.currentTarget.dataset.rank;
    this.setData({typeId, activeIndex:rank});
    this.initData();
    this.getList();
  },
  // 获取我的积分
  userInfo() {
    let { userId } = this.data
    App.HttpService.userInfo({ userId: userId }).then(res => {
      let data = res.data
      if (data.code == 200) {
        this.setData({ detail: data.data })
      }
    })
  },
})
